package com.techwells.learningkites.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.R.integer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.techwells.learningkites.R;
import com.techwells.learningkites.cache.BaseUserCenter;
import com.techwells.learningkites.model.LoginViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.ReturnCode;
import com.techwells.taco.base.CommonBaseActivity;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.mvvm.ViewModelManager;
import com.techwells.taco.net.HttpConnectionUtils;
import com.techwells.taco.net.HttpHandler;
import com.techwells.taco.networkmodel.BaseUser;
import com.techwells.taco.networkservice.ServiceMediator;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.utils.Base64;
import com.techwells.taco.utils.Base64Coder;
import com.techwells.taco.utils.CommonUtil;
import com.techwells.taco.utils.ToastUtils;

public class LoginActivity extends CommonBaseActivity implements OnClickListener {
	
	private EditText username,password;
	private TextView btnRegister,btnForgetpassword,btnLogin;
	private LoginViewModel presentModel;
	private ImageView leftImg;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		//LoginViewModel presentModel = (LoginViewModel) ViewModelManager.manager().newViewModel(LoginActivity.class.getName());
		//setViewModel(presentModel);
		initTitleBar(R.string.login, this);
		initViews();
	}

	private void initViews() {
		leftImg = (ImageView) findViewById(R.id.common_activity_title_left_image);
		leftImg.setVisibility(View.GONE);
		
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);
		btnRegister = (TextView) findViewById(R.id.btn_register);
		btnRegister.setOnClickListener(this);
		btnForgetpassword = (TextView) findViewById(R.id.btn_forgetpassword);
		btnForgetpassword.setOnClickListener(this);
		btnLogin = (TextView) findViewById(R.id.btn_login);
		btnLogin.setOnClickListener(this);
	}

	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_forgetpassword:
			Route.route().nextController(LoginActivity.this, ForgetPasswordActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			break;
		case R.id.btn_login:
//			Route.route().nextController(LoginActivity.this, MainPageActivity.class.getName(), Route.WITHOUT_RESULTCODE);
			String name = username.getText().toString();
			String ps =  password.getText().toString();
			if (name.isEmpty() || ps.isEmpty()) {
				Toast.makeText(LoginActivity.this, "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
			}else{
			doRequest2();
			}
			break;
		case R.id.btn_register:
			Route.route().nextController(LoginActivity.this, RegisterAcitivity.class.getName(), Route.WITHOUT_RESULTCODE);
			break;

		default:
			break;
		}
		
	}
	
	

	private void doRequest() {
//		HashMap<String, String> argMap = new HashMap<String, String>();	
//		argMap.put("username", username.getText().toString());
//		argMap.put("password",password.getText().toString());
//		argMap.put("t","1425368505476");
		//doTask(KitesServiceMediator.SERVICE_DO_LOGIN,argMap);
		
		String name = username.getText().toString();
		String ps =  password.getText().toString();
//		String pwd = Base64.encode(ps.getBytes());
//		long time = System.currentTimeMillis();
		
		//String signMd = generateSignParam(buildLoginParams(name, pwd, time));

		
		//String sign = "password="+pwd+"t="+time+"username="+name;
		/*
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		
		parameters.add(new BasicNameValuePair("username",name));
		parameters.add(new BasicNameValuePair("password", pwd));
		
		parameters.add(new BasicNameValuePair("t", ""+time));
		parameters.add(new BasicNameValuePair("sign", ""+signMd));
		
		*/
		
		
		ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("username", name));
		String p = Base64Coder.encodeString(ps);
		parameters.add(new BasicNameValuePair("password", p));
		String t = ""+System.currentTimeMillis();
		parameters.add(new BasicNameValuePair("t", t));
		
		
		String sign = "password="+p+"t="+t+"username="+name;
		String signMd = CommonUtil.MD5Encrypt(sign);
		parameters.add(new BasicNameValuePair("sign", signMd));		
		
		new HttpConnectionUtils(loginHandler).post(KitesRequestUrl.DO_LOGIN, parameters);
	}
	
	private void doRequest2() {
		String name = username.getText().toString();
		String ps =  password.getText().toString();
		String p = Base64Coder.encodeString(ps);
		String t = ""+System.currentTimeMillis();
		String sign = "password="+p+"t="+t+"username="+name;
		String signMd = CommonUtil.MD5Encrypt(sign);
		
		HashMap<String, String> argMap = new HashMap<String, String>();	
		argMap.put("username", name);
		argMap.put("password", p);
		argMap.put("t", t);
		argMap.put("sign", signMd);
		
		doTask(KitesServiceMediator.SERVICE_DO_LOGIN,argMap);
		
	}
	
	private Handler loginHandler = new HttpHandler(LoginActivity.this){
		protected void succeed(JSONObject jObject) {
			super.succeed(jObject);
			int state = jObject.optInt("state");
			if (state == 200) {
				
//				SaveSP.SaveState(Login.this, true);
				Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
				Route.route().nextController(LoginActivity.this, MainPageActivity.class.getName(), Route.WITHOUT_RESULTCODE);
				LoginActivity.this.finish();
			} else {
				Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//				SaveSP.saveUser(getBaseContext(), 0);
			}		
		}
	};
	
	
	
	private Map<String, String> buildLoginParams(String userName, String password, long t) {
        Map<String, String> params = new TreeMap<String, String>();
        params.put("username", "userName");
        params.put("password", Base64.encode(password.getBytes()));
        params.put("t", t + "");
        return params;
    }
    
	private String generateSignParam(Map<String, String> params) {
        StringBuffer sb = new StringBuffer();
        for(String k : params.keySet()) {
            String v = params.get(k);
            sb.append(k);
            sb.append("=");
            sb.append(v);
        }
        String signContent = sb.toString();
        String sign = CommonUtil.MD5Encrypt(signContent);
        return sign;
    }
	
	
	@Override
	public void alreadyBindBaseViewModel() {
		super.alreadyBindBaseViewModel();
		presentModel = (LoginViewModel) baseViewModel;
	}
	
	@Override
	public void refreshData(TaskToken token) {
		super.refreshData(token);
		
		String method = token.method;
		if(method.equals(KitesServiceMediator.SERVICE_DO_LOGIN))
		{
			int returnCode = ((LoginViewModel) baseViewModel).returnCode;
			if (returnCode == ServiceMediator.Service_Return_Success) {
				ToastUtils.show(this, "登录成功");
//				BaseUserCenter.getInstance().setUser(new BaseUser());
//				BaseUserCenter.getInstance().getUser().loginId = username.getText().toString();
				Route.route().nextController(LoginActivity.this, MainPageActivity.class.getName(), Route.WITHOUT_RESULTCODE);
				finish();
			}
		}
		
	}

	
	@Override
	public void requestFailedHandle(TaskToken token, int errorCode,
			String errorMsg) {
		
		switch (errorCode) {
		case 10001:
			ToastUtils.show(this, "用户名错误");
			break;
		case 10002:
			ToastUtils.show(this, "密码错误");
			break;

		default:
			ToastUtils.show(this, errorMsg);
			break;
		}
		
	}
	
//	@Override
//	public void onBackPressed() {
//		// TODO Auto-generated method stub
//	}
	
}
